package com.gan.controller;

import com.gan.entity.InfluxPosition;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

public class InfluxDB2Example {

  public static void main(String[] args) {

    InfluxDBClient client = InfluxDBClientFactory.create("http://mytencent:8086",
            "lWizDhyENfSGSU8z7ACce_l2WsBNh5lWCL9TOrDbNhBFbDlafIeHU0o3BOtBdSUZpiXBPQcXgd6PpKk5rDT50w==".toCharArray(),
            "dk",
            "mydb_1");
    writeData(client);
    List<FluxTable> query = queryData(client);
    for (FluxTable table : query) {
      List<FluxRecord> records = table.getRecords();
      for (FluxRecord record : records) {
        System.out.println("values:" + record.getValues() + "---time:" + record.getTime());
      }
    }
  }

  private static void writeData(InfluxDBClient client) {
    WriteApiBlocking writeApiBlocking = client.getWriteApiBlocking();
    List<InfluxPosition> list = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      InfluxPosition position = new InfluxPosition()
              .setDeviceId("123")
              .setVehicleId("321")
              .setLocationTime(Instant.now())
              .setLongitude(new BigDecimal("113.12313"))
              .setLatitude(new BigDecimal("23.8524"))
              .setSpeed(i * 10)
              .setAltitude(i * 100)
              .setMileage(i * 1000);
      list.add(position);
    }
    writeApiBlocking.writeMeasurements("mydb_1", "dk", WritePrecision.MS, list);
  }

  private static List<FluxTable> queryData(InfluxDBClient client) {
    String flux = "from(bucket: \"mydb_1\") |> range(start: -6h) |> filter(fn: (r) => r[\"_measurement\"] == \"device_history_location\") |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")";
    List<FluxTable> query = client.getQueryApi().query(flux);
    for (FluxTable table : query) {
      List<FluxRecord> records = table.getRecords();
      for (FluxRecord record : records) {
        System.out.println(record.getMeasurement() + "---" + record.getField() + "---" + record.getValue() + "---" + record.getTime());
      }
    }
    return query;
  }



}